<!-- 仿真推演控制台 - 分组件版本 -->
<template>
  <div class="simulation-console">
    <!-- 顶部工具栏 -->
    <div class="console-header">
      <div class="header-left">
        <h1 class="console-title">
          <el-icon class="title-icon"><VideoPlay /></el-icon>
          仿真推演控制台
        </h1>
        <div class="simulation-info">
          <el-tag type="info" size="small">{{ currentSimulation.name }}</el-tag>
          <el-tag :type="simulationStatus.type" size="small">
            <el-icon><Timer /></el-icon>
            {{ simulationStatus.text }}
          </el-tag>
        </div>
      </div>

      <div class="header-actions">
        <el-button-group class="action-group">
          <el-button size="small" @click="pauseSimulation" :disabled="!isRunning">
            <el-icon><VideoPause /></el-icon>
            暂停
          </el-button>
          <el-button size="small" @click="resumeSimulation" :disabled="isRunning">
            <el-icon><VideoPlay /></el-icon>
            继续
          </el-button>
          <el-button size="small" @click="stopSimulation">
            <el-icon><TurnOff /></el-icon>
            停止
          </el-button>
          <el-button size="small" type="primary" @click="resetSimulation">
            <el-icon><RefreshRight /></el-icon>
            重置
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 主控制区域 -->
    <div class="console-content">
      <!-- 左侧时空推进控制器 -->
      <el-aside :width="leftPanelWidth" class="control-panel">
        <div class="panel-header">
          <h3>时空推进控制器</h3>
        </div>
        
        <TimeController
          :current-time="currentTime"
          :start-time="startTime"
          :end-time="endTime"
          :time-scale="timeScale"
          @update:current-time="currentTime = $event"
          @update:time-scale="timeScale = $event"
          @time-change="handleTimeChange"
          @speed-change="handleSpeedChange"
        />

        <!-- 面板调整器 -->
        <div
          class="panel-resizer left-resizer"
          @mousedown="startResize('left', $event)"
        ></div>
      </el-aside>

      <!-- 中央多视角观察区 -->
      <el-main class="observation-area">
        <ObservationArea
          :platform-data="platformData"
          :signal-data="signalData"
          :electromagnetic-data="electromagneticData"
          @view-tab-change="handleViewTabChange"
          @platform-view-change="handlePlatformViewChange"
          @platform-center="handlePlatformCenter"
          @platform-fullscreen="handlePlatformFullscreen"
          @signal-spectrum-reset="handleSignalSpectrumReset"
          @signal-spectrum-export="handleSignalSpectrumExport"
          @signal-waveform-reset="handleSignalWaveformReset"
          @signal-waveform-export="handleSignalWaveformExport"
          @em-time-freq-reset="handleEmTimeFreqReset"
          @em-time-freq-mode-toggle="handleEmTimeFreqModeToggle"
          @em-relation-reset="handleEmRelationReset"
          @em-relation-export="handleEmRelationExport"
        />
      </el-main>

      <!-- 右侧数据面板 -->
      <el-aside :width="rightPanelWidth" class="data-side-panel">
        <DataPanel
          :platform-data="platformData"
          :signal-stats="signalStats"
          :event-log="eventLog"
          :simulation-duration="simulationDuration"
          @tab-change="handleDataTabChange"
          @clear-logs="handleClearLogs"
          @generate-report="handleGenerateReport"
          @export-data="handleExportData"
        />

        <!-- 面板调整器 -->
        <div
          class="panel-resizer right-resizer"
          @mousedown="startResize('right', $event)"
        ></div>
      </el-aside>
    </div>

    <!-- 底部状态栏 -->
    <div class="console-footer">
      <div class="status-left">
        <div class="status-item">
          <el-icon><Clock /></el-icon>
          <span>仿真时间: {{ formatTime(currentTime) }}</span>
        </div>
        <div class="status-item">
          <el-icon><Cpu /></el-icon>
          <span>CPU: {{ systemStats.cpu }}%</span>
        </div>
        <div class="status-item">
          <el-icon><Monitor /></el-icon>
          <span>内存: {{ systemStats.memory }}%</span>
        </div>
      </div>

      <div class="status-right">
        <div class="fps-indicator">
          <el-icon><Grid /></el-icon>
          <span>FPS: {{ renderStats.fps }}</span>
        </div>
        <div class="connection-status">
          <el-icon class="connection-icon" :class="{ active: isConnected }">
            <Connection />
          </el-icon>
          <span>{{ isConnected ? '已连接' : '连接中断' }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import {
  VideoPlay,
  VideoPause,
  TurnOff,
  Timer,
  RefreshRight,
  Clock,
  Monitor,
  Cpu,
  Grid,
  Connection
} from '@element-plus/icons-vue'

// 导入组件
import TimeController from './components/simulation/TimeController.vue'
import ObservationArea from './components/simulation/ObservationArea.vue'
import DataPanel from './components/simulation/DataPanel.vue'

// 仿真状态
const isRunning = ref(false)
const currentTime = ref(0)
const startTime = ref(0)
const endTime = ref(86400) // 24小时
const timeScale = ref(1)

// 面板宽度
const leftPanelWidth = ref('25vw')
const rightPanelWidth = ref('25vw')

// 仿真信息
const currentSimulation = reactive({
  name: '电磁对抗演练-001',
  startTime: new Date(),
  duration: 86400
})

// 平台数据
const platformData = ref([
  {
    id: 1,
    name: '舰船-001',
    status: 'active',
    position: '38.9°N, 121.6°E',
    speed: 25,
    heading: 45
  },
  {
    id: 2,
    name: '战机-001',
    status: 'active',
    position: '39.1°N, 121.8°E',
    speed: 450,
    heading: 180
  }
])

// 信号数据
const signalData = ref({})

// 电磁环境数据
const electromagneticData = ref({})

// 信号统计
const signalStats = reactive({
  totalSignals: 156,
  threats: 12,
  identified: 89
})

// 事件日志
const eventLog = ref([
  {
    id: 1,
    timestamp: Date.now() - 300000,
    type: 'threat',
    title: '威胁信号检测',
    description: '检测到未知雷达信号，频率8.5GHz'
  },
  {
    id: 2,
    timestamp: Date.now() - 180000,
    type: 'warning',
    title: '信号强度异常',
    description: '通信信号强度下降至-85dBm'
  },
  {
    id: 3,
    timestamp: Date.now() - 60000,
    type: 'info',
    title: '目标识别完成',
    description: '成功识别目标类型：驱逐舰'
  }
])

// 系统状态
const systemStats = reactive({
  cpu: 45,
  memory: 67
})

// 渲染统计
const renderStats = reactive({
  fps: 60
})

const isConnected = ref(true)

// 计算属性
const simulationStatus = computed(() => {
  if (isRunning.value) {
    return { type: 'success', text: '运行中' }
  } else {
    return { type: 'warning', text: '已暂停' }
  }
})

const simulationDuration = computed(() => {
  return currentTime.value
})

// 调整面板大小相关
let isResizing = false
let resizeType = null
let startX = 0
let startWidth = 0

// 方法定义
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 仿真控制方法
const pauseSimulation = () => {
  isRunning.value = false
  ElMessage.info('仿真已暂停')
}

const resumeSimulation = () => {
  isRunning.value = true
  ElMessage.success('仿真已继续')
}

const stopSimulation = () => {
  isRunning.value = false
  currentTime.value = 0
  ElMessage.warning('仿真已停止')
}

const resetSimulation = () => {
  isRunning.value = false
  currentTime.value = 0
  ElMessage.success('仿真已重置')
}

// 时间控制事件处理
const handleTimeChange = (newTime) => {
  // 处理时间变化
  console.log('时间变化:', newTime)
}

const handleSpeedChange = (newSpeed) => {
  // 处理速度变化
  console.log('速度变化:', newSpeed)
}

// 视角切换事件处理
const handleViewTabChange = (tabName) => {
  console.log('视角切换:', tabName)
}

// 平台视角事件处理
const handlePlatformViewChange = (data) => {
  console.log('平台视角变化:', data)
}

const handlePlatformCenter = () => {
  ElMessage.info('地图已居中')
}

const handlePlatformFullscreen = () => {
  ElMessage.info('切换全屏模式')
}

// 信号视角事件处理
const handleSignalSpectrumReset = () => {
  ElMessage.info('频谱图已重置')
}

const handleSignalSpectrumExport = () => {
  ElMessage.success('频谱数据已导出')
}

const handleSignalWaveformReset = () => {
  ElMessage.info('波形图已重置')
}

const handleSignalWaveformExport = () => {
  ElMessage.success('波形数据已导出')
}

// 电磁环境视角事件处理
const handleEmTimeFreqReset = () => {
  ElMessage.info('时频图已重置')
}

const handleEmTimeFreqModeToggle = (mode) => {
  ElMessage.info(`时频图切换为${mode}模式`)
}

const handleEmRelationReset = () => {
  ElMessage.info('关系图谱已重置')
}

const handleEmRelationExport = () => {
  ElMessage.success('关系图谱已导出')
}

// 数据面板事件处理
const handleDataTabChange = (tabName) => {
  console.log('数据面板切换:', tabName)
}

const handleClearLogs = () => {
  eventLog.value = []
}

const handleGenerateReport = () => {
  // 生成报告逻辑
}

const handleExportData = () => {
  // 导出数据逻辑
}

// 面板调整大小
const startResize = (type, event) => {
  isResizing = true
  resizeType = type
  startX = event.clientX
  startWidth = type === 'left' ?
    parseFloat(leftPanelWidth.value) :
    parseFloat(rightPanelWidth.value)

  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
  document.body.style.cursor = 'col-resize'
}

const handleResize = (event) => {
  if (!isResizing) return

  const deltaX = event.clientX - startX
  const deltaVw = (deltaX / window.innerWidth) * 100

  if (resizeType === 'left') {
    const newWidth = Math.max(20, Math.min(40, startWidth + deltaVw))
    leftPanelWidth.value = `${newWidth}vw`
  } else if (resizeType === 'right') {
    const newWidth = Math.max(20, Math.min(40, startWidth - deltaVw))
    rightPanelWidth.value = `${newWidth}vw`
  }
}

const stopResize = () => {
  isResizing = false
  resizeType = null
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
  document.body.style.cursor = 'default'
}

// 模拟仿真循环
const simulationLoop = () => {
  if (isRunning.value) {
    currentTime.value += timeScale.value
    
    if (currentTime.value >= endTime.value) {
      currentTime.value = endTime.value
      isRunning.value = false
      ElMessage.success('仿真推演完成')
    }
  }
}

// 生命周期钩子
onMounted(() => {
  // 启动仿真循环
  const intervalId = setInterval(simulationLoop, 1000)
  
  // 模拟系统状态更新
  const statusInterval = setInterval(() => {
    systemStats.cpu = Math.floor(Math.random() * 30) + 40
    systemStats.memory = Math.floor(Math.random() * 20) + 60
    renderStats.fps = Math.floor(Math.random() * 10) + 55
  }, 2000)
  
  onBeforeUnmount(() => {
    clearInterval(intervalId)
    clearInterval(statusInterval)
    document.removeEventListener('mousemove', handleResize)
    document.removeEventListener('mouseup', stopResize)
  })
})
</script>

<style scoped>
/* 主容器 - 适配侧边栏布局 */
.simulation-console {
  width: 96vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #1f2d3d;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 4vw;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 顶部工具栏 */
.console-header {
  height: 7vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2vw;
  background: linear-gradient(135deg, #263445, #1f2d3d);
  border-bottom: 1px solid #2d3a4b;
  box-shadow: 0 0.2vh 0.8vh rgba(0, 0, 0, 0.3);
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.console-title {
  margin: 0;
  font-size: 1.4rem;
  font-weight: 600;
  color: #bfcbd9;
  display: flex;
  align-items: center;
  gap: 1vw;
}

.title-icon {
  font-size: 1.6rem;
  color: var(--el-color-primary);
}

.simulation-info {
  display: flex;
  align-items: center;
  gap: 0.8vw;
}

.header-actions {
  display: flex;
  gap: 1vw;
}

.action-group .el-button {
  height: 3.5vh;
  font-size: 0.85rem;
}

/* 主控制区域 */
.console-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  min-height: 0;
}

/* 左侧控制面板 */
.control-panel {
  background: #263445;
  border-right: 1px solid #2d3a4b;
  position: relative;
  min-width: 20vw;
  max-width: 40vw;
  flex-shrink: 0;
}

.panel-header {
  height: 5vh;
  display: flex;
  align-items: center;
  padding: 0 1.5vw;
  background: #1f2d3d;
  border-bottom: 1px solid #2d3a4b;
}

.panel-header h3 {
  margin: 0;
  font-size: 1rem;
  color: #bfcbd9;
}

/* 中央观察区域 */
.observation-area {
  flex: 1;
  padding: 0;
  background: #0a0f1b;
  position: relative;
  overflow: hidden;
}

/* 右侧数据面板 */
.data-side-panel {
  background: #263445;
  border-left: 1px solid #2d3a4b;
  position: relative;
  min-width: 20vw;
  max-width: 40vw;
  flex-shrink: 0;
}

/* 面板调整器 */
.panel-resizer {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 0.4vw;
  background: transparent;
  cursor: col-resize;
  z-index: 5;
  transition: background-color 0.2s ease;
}

.left-resizer {
  right: -0.2vw;
}

.right-resizer {
  left: -0.2vw;
}

.panel-resizer:hover {
  background: #409EFF;
}

/* 底部状态栏 */
.console-footer {
  height: 5vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2vw;
  background: #1f2d3d;
  border-top: 1px solid #2d3a4b;
  font-size: 0.8rem;
}

.status-left,
.status-right {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  color: #bfcbd9;
}

.fps-indicator {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  color: #bfcbd9;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 0.5vw;
}

.connection-icon {
  font-size: 0.9rem;
  color: var(--el-color-warning);
  transition: color 0.3s ease;
}

.connection-icon.active {
  color: var(--el-color-success);
}

/* Element Plus 深色主题覆盖 */
.simulation-console :deep(.el-button) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.simulation-console :deep(.el-button:hover) {
  background: #2d3a4b !important;
  border-color: #409EFF !important;
  color: #409EFF !important;
}

.simulation-console :deep(.el-button--primary) {
  background: #409EFF !important;
  border-color: #409EFF !important;
  color: #ffffff !important;
}

.simulation-console :deep(.el-button--primary:hover) {
  background: #66B2FF !important;
  border-color: #66B2FF !important;
}

.simulation-console :deep(.el-button:disabled) {
  background: #1f2d3d !important;
  border-color: #2d3a4b !important;
  color: #8591a3 !important;
}

.simulation-console :deep(.el-tag) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.simulation-console :deep(.el-tag--success) {
  background: #1f4838 !important;
  border-color: #2d5a41 !important;
  color: #67C23A !important;
}

.simulation-console :deep(.el-tag--warning) {
  background: #483d1f !important;
  border-color: #5a4a2d !important;
  color: #E6A23C !important;
}

.simulation-console :deep(.el-tag--info) {
  background: #1f2d3d !important;
  border-color: #2d3a4b !important;
  color: #909399 !important;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .control-panel {
    min-width: 20vw;
  }
  
  .data-side-panel {
    min-width: 20vw;
  }
}

@media (max-width: 1200px) {
  .console-title {
    font-size: 1.2rem;
  }

  .simulation-info {
    display: none;
  }

  .control-panel {
    min-width: 22vw;
  }
  
  .data-side-panel {
    min-width: 22vw;
  }
}

@media (max-width: 768px) {
  .simulation-console {
    width: 100vw;
    left: 0;
  }
  
  .console-header {
    height: 8vh;
    padding: 0 1vw;
  }

  .control-panel,
  .data-side-panel {
    min-width: 25vw;
  }
}
</style>

<!-- 全局样式覆盖 -->
<style>
/* 全局 Element Plus 下拉组件深色主题 */
.el-select-dropdown {
  background: #263445 !important;
  border-color: #2d3a4b !important;
}

.el-select-dropdown__item {
  background: #263445 !important;
  color: #bfcbd9 !important;
}

.el-select-dropdown__item:hover {
  background: #2d3a4b !important;
  color: #409EFF !important;
}

.el-select-dropdown__item.selected {
  background: #409EFF !important;
  color: #ffffff !important;
}

.el-popper {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.el-tooltip__popper {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}
</style>